package com.hanbang.taitaigou.ui.activity.aboutme.myOrder;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.GetOrderComment;
import com.hanbang.taitaigou.model.GetOrderList;
import com.hanbang.taitaigou.model.GoodsDetail;
import com.hanbang.taitaigou.ui.activity.aboutme.address.AboutMeAddAddressManagementActivity;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.gouwuche.AboutMyOrderCommitActivity;
import com.hanbang.taitaigou.ui.activity.home.AddAddressActivity;
import com.hanbang.taitaigou.ui.activity.home.MainActivity;
import com.hanbang.taitaigou.ui.widget.HorizontalListView;
import com.hanbang.taitaigou.ui.widget.autoloadding.ListViewForAutoLoad;
import com.hanbang.taitaigou.ui.widget.autoloadding.OnLoaddingListener;
import com.hanbang.taitaigou.ui.widget.dialog.BaseDialog;
import com.hanbang.taitaigou.ui.widget.dialog.OnClickCallback;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.http.PagingHelp;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单列表
 * Created by fanxin on 2016/3/21.
 */
public class AboutMyOrderActivity extends BaseActivity {
    /**
     * listview
     **/
    private ListViewForAutoLoad listView;
    private List<GetOrderList> list;
    private ListViewAdapter listViewAdapter;
    private List<GoodsDetail> gridlist;
    private int selectIndex;
    private GetOrderComment getOrderComment = null;


    private FrameLayout fl_dingdan_list;
    private Button bt_qgg;

    //订单号id对应的position
    private int orderPosition = -1;
    private int addressID = -1;

    /**
     * 页码
     **/
    private PagingHelp pageHelp;


    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout valueSwipeRefreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_my_order);
        initView();
        setOnClickListener();
        getOrderList(true);
    }

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {

        bt_qgg.setOnClickListener(onClickListener);
    }

    @SuppressWarnings("unused")
    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_qgg:
                    Intent intent = new Intent();
                    intent.setClass(AboutMyOrderActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题
        setTop(null, 0, getString(R.string.top_my_order), null, 0);
        setBackArrows(findViewById(R.id.top_bar_left_iv));
        listView = (ListViewForAutoLoad) findViewById(R.id.lv_order_list);
        fl_dingdan_list = (FrameLayout) findViewById(R.id.fl_dingdan_list);
        bt_qgg = (Button) findViewById(R.id.bt_qgg);
        valueSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.id_swipe_ly_right);
        shuaxin();

        listView.setOnLoaddingListener(new OnLoaddingListener() {
            @Override
            public void onLoadding() {
                getOrderList(false);
            }
        }, pageHelp = new PagingHelp(this));

        list = new ArrayList<GetOrderList>();
        listViewAdapter = new ListViewAdapter();
        listView.setAdapter(listViewAdapter);

    }

    Date date = new Date(0);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String time = sdf.format(date);


    /**
     * 下拉刷新
     */

    private void shuaxin() {
        valueSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getOrderList(true);
            }
        });
    }

    /**
     * 获取所以的订单数据
     */
    private void getOrderList(boolean isDiyiCi) {
        if (isDiyiCi) {
            pageHelp.clear();
            list.clear();
        }
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetOrderList");
        httpRequestParams.addUserId(userData);
        httpRequestParams.addBodyParameter("order_type", String.valueOf(0));
//        httpRequestParams.addBodyParameter("page_index", String.valueOf(pageHelp.getPageindex()));
        httpRequestParams.addBodyParameter("page_index", String.valueOf(pageHelp.getPageindex()));
        httpRequestParams.addBodyParameter("Pagesize", String.valueOf(pageHelp.getPageCount()));
//        httpRequestParams.addBodyParameter("begin_date", time);
//        httpRequestParams.addBodyParameter("end_date", dateUtils.currentDate2StringByDay());
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray js = jsonObject.getJSONArray("result");

                    list.addAll(pageHelp.getValidData(JsonHelper.parseCollection(js, ArrayList.class, GetOrderList.class)));
                    listView.loaddingFinsh();
                    listViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.setSwipeRefreshLayout(valueSwipeRefreshLayout));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1000 && resultCode==RESULT_OK){
            listViewAdapter.notifyDataSetChanged();
        }
        if(requestCode == 999 && resultCode == 1001){
            addressID = data.getIntExtra("addressID", addressID);
            HttpRequestParams httpRequestParams = new HttpRequestParams("UpdateOrderStatus");
            httpRequestParams.addUserId(userData);
            httpRequestParams.addBodyParameter("order_id", String.valueOf(list.get(orderPosition).getId()));
            httpRequestParams.addBodyParameter("edit_type","update_address");
            httpRequestParams.addBodyParameter("address_id",String.valueOf(addressID));
            httpManager.post(httpRequestParams, new HttpCallBack<String>(this,"") {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    getOrderList(true);
                }
            });
        }
    }

    class ListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (list.size() <= 0) {
                fl_dingdan_list.setVisibility(View.VISIBLE);
                valueSwipeRefreshLayout.setVisibility(View.GONE);
            } else {
                fl_dingdan_list.setVisibility(View.GONE);
                valueSwipeRefreshLayout.setVisibility(View.VISIBLE);
            }
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(AboutMyOrderActivity.this, R.layout.item_about_my_order);
                viewHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                viewHolder.gridView = (HorizontalListView) convertView.findViewById(R.id.grid);
                viewHolder.tv_money = (TextView) convertView.findViewById(R.id.tv_money);
                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.tv_tel = (TextView) convertView.findViewById(R.id.tv_phone);
                viewHolder.tv_address = (TextView) convertView.findViewById(R.id.tv_address);
                viewHolder.bt_cancel_order = (Button) convertView.findViewById(R.id.bt_cancel_order);
                viewHolder.bt_commit = (Button) convertView.findViewById(R.id.bt_commit);
                viewHolder.bt_confirm_receipt = (Button) convertView.findViewById(R.id.bt_confirm_receipt);
                viewHolder.bt_evaluate = (Button) convertView.findViewById(R.id.bt_evaluate);
                viewHolder.bt_return_goods = (Button) convertView.findViewById(R.id.bt_return_goods);
                viewHolder.ll_update_address = (LinearLayout)convertView.findViewById(R.id.ll_update_address);
                viewHolder.tv_ddzt = (TextView)convertView.findViewById(R.id.tv_ddzt);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //获取数据
            selectIndex = position;
            //获取时间
            viewHolder.tv_time.setText("日期:" + list.get(position).getAdd_time());

            //获取订单金额
            viewHolder.tv_money.setText("总价:￥" + list.get(position).getOrder_amount());
            //获取人名电话地址
            viewHolder.tv_name.setText("收货人姓名："+list.get(position).getAccept_name());
            viewHolder.tv_tel.setText("收货人电话："+list.get(position).getMobile());
            viewHolder.tv_address.setText("收货人地址："+list.get(position).getProvince()
                    + list.get(position).getCity()
                    + list.get(position).getArea()
                    + list.get(position).getAddress());
            //判断 结账，取消订单，确认收货，评价，退货

            /**
             *   "status":1, //（1：已生成,2:已提交。3:已确认 ，4：订单完成，5:订单取消，6:已退货，）
             "payment_id":1,// 支付方式(0货到付款，1，线上支付,2,未选择)
             "payment_status":0,// 支付状态（0未支付，1，已支付，2，支付处理中，3：已退款）
             "express_status":0, //发货状态,0未发货,1已发货
             */
            /**
             private Button bt_cancel_order;//取消订单
             private Button bt_commit;//结算
             private Button bt_confirm_receipt;//确认收货
             private Button bt_evaluate;//评价
             private Button bt_return_goods;//退货
             */
            switch (list.get(position).getPayment_status()){
                case 0:
                    viewHolder.tv_ddzt.setText("未支付");
                    viewHolder.bt_cancel_order.setVisibility(View.VISIBLE);
                    viewHolder.bt_commit.setVisibility(View.VISIBLE);
                    viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                    viewHolder.bt_evaluate.setVisibility(View.GONE);
                    viewHolder.bt_return_goods.setVisibility(View.GONE);
                    break;
                case 1:
                    viewHolder.tv_ddzt.setText("已支付");
                    viewHolder.bt_cancel_order.setVisibility(View.GONE);
                    viewHolder.bt_commit.setVisibility(View.GONE);
                    viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                    viewHolder.bt_evaluate.setVisibility(View.GONE);
                    viewHolder.bt_return_goods.setVisibility(View.GONE);
                    if(list.get(position).getStatus() == 3){
                        viewHolder.tv_ddzt.setText("商家已接单");
                        viewHolder.bt_cancel_order.setVisibility(View.GONE);
                        viewHolder.bt_commit.setVisibility(View.GONE);
                        viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                        viewHolder.bt_evaluate.setVisibility(View.GONE);
                        viewHolder.bt_return_goods.setVisibility(View.GONE);
                        if(list.get(position).getExpress_status() == 0){
                            viewHolder.tv_ddzt.setText("商家未发货");
                            viewHolder.bt_cancel_order.setVisibility(View.GONE);
                            viewHolder.bt_commit.setVisibility(View.GONE);
                            viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                            viewHolder.bt_evaluate.setVisibility(View.GONE);
                            viewHolder.bt_return_goods.setVisibility(View.GONE);
                        }else if(list.get(position).getExpress_status() == 1){
                            viewHolder.tv_ddzt.setText("商家已发货");
                            viewHolder.bt_cancel_order.setVisibility(View.GONE);
                            viewHolder.bt_commit.setVisibility(View.GONE);
                            viewHolder.bt_confirm_receipt.setVisibility(View.VISIBLE);
                            viewHolder.bt_evaluate.setVisibility(View.GONE);
                            viewHolder.bt_return_goods.setVisibility(View.GONE);

                        }
                    }else if(list.get(position).getStatus() == 4){
                        viewHolder.tv_ddzt.setText("订单已完成");
                        viewHolder.bt_cancel_order.setVisibility(View.GONE);
                        viewHolder.bt_commit.setVisibility(View.GONE);
                        viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                        viewHolder.bt_evaluate.setVisibility(View.VISIBLE);
                        viewHolder.bt_return_goods.setVisibility(View.VISIBLE);
                    }else if(list.get(position).getStatus() == 5){
                        viewHolder.tv_ddzt.setText("订单已取消");
                        viewHolder.bt_cancel_order.setVisibility(View.VISIBLE);
                        viewHolder.bt_commit.setVisibility(View.GONE);
                        viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                        viewHolder.bt_evaluate.setVisibility(View.GONE);
                        viewHolder.bt_return_goods.setVisibility(View.GONE);
                    }else if(list.get(position).getStatus() == 6){
                        viewHolder.tv_ddzt.setText("已退货");
                        viewHolder.bt_cancel_order.setVisibility(View.VISIBLE);
                        viewHolder.bt_commit.setVisibility(View.GONE);
                        viewHolder.bt_confirm_receipt.setVisibility(View.GONE);
                        viewHolder.bt_evaluate.setVisibility(View.GONE);
                        viewHolder.bt_return_goods.setVisibility(View.GONE);
                    }
                    break;

            }


            //评价
            viewHolder.bt_evaluate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HttpRequestParams httpRequestParams = new HttpRequestParams("GetOrderComment");
                    httpRequestParams.addUserId(userData);
                    httpRequestParams.addBodyParameter("Order_id", String.valueOf(list.get(position).getId()));
                    httpManager.post(httpRequestParams, new HttpCallBack<String>(AboutMyOrderActivity.this, "正在获取...") {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getInt("status") == 1) {
                                    JSONArray js = jsonObject.getJSONArray("result");

                                    if (js.length() > 0) {
                                        getOrderComment = JsonHelper.parseObject(js.getJSONObject(0), GetOrderComment.class);
                                        if(getOrderComment.getIs_comment() == 1){
                                            ToastUtils.show(AboutMyOrderActivity.this,"您已评价过",Toast.LENGTH_LONG);
                                        }else{
                                            Intent intent = new Intent();
                                            intent.putExtra("Order_id", String.valueOf(list.get(position).getId()));
                                            intent.setClass(AboutMyOrderActivity.this, AboutMyOrderEvaluateActivity.class);
                                            startActivityForResult(intent,1000);
                                        }
                                    } else {
                                        Intent intent = new Intent();
                                        intent.putExtra("Order_id", String.valueOf(list.get(position).getId()));
                                        intent.setClass(AboutMyOrderActivity.this, AboutMyOrderEvaluateActivity.class);
                                        startActivityForResult(intent, 1000);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
            //结算
            viewHolder.bt_commit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(AboutMyOrderActivity.this, AboutMyOrderCommitActivity.class);
//                    intent.putExtra("User_id",userData.getUser_id());
                    intent.putExtra("order_id", list.get(position).getId());
                    intent.putExtra("zongjia", list.get(position).getOrder_amount());
                    intent.putExtra("order_no",list.get(position).getOrder_no());
                    startActivity(intent);
                }
            });
            //确认收货
            viewHolder.bt_confirm_receipt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseDialog dialog = new BaseDialog(AboutMyOrderActivity.this, BaseDialog.MODE.CONFIRM);
                    dialog.setTitleMain("提示");
                    dialog.setMainColor(getResources().getColor(R.color.red));
                    dialog.setContent("订单号:" + list.get(position).getOrder_no() + "即将完成.");
                    dialog.setOnClickCallback(new OnClickCallback() {
                        @Override
                        public void onClick(BaseDialog dialog, Object number, Object content) {
                            if ((Integer) number == 2) {
                                if ((AboutMyOrderActivity.this).isLogin(true)) {
                                    HttpRequestParams params = new HttpRequestParams("UpdateOrderStatus");
                                    params.addUserId(userData);
                                    params.addBodyParameter("order_id", String.valueOf(list.get(position).getId()));
                                    params.addBodyParameter("edit_type", "confirm_receipt");
                                    x.http().post(params, new HttpCallBack<String>(AboutMyOrderActivity.this, AboutMyOrderActivity.this.getString(R.string.loadding), false) {
                                        @Override
                                        public void onSuccess(String result) {
                                            super.onSuccess(result);
//                                            listViewAdapter.notifyDataSetChanged();
                                            getOrderList(true);
                                        }
                                    });
                                }
                            }
                        }
                    });
                    dialog.show();
                }
            });

            //退货
            viewHolder.bt_return_goods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseDialog dialog = new BaseDialog(AboutMyOrderActivity.this, BaseDialog.MODE.CONFIRM);
                    dialog.setTitleMain("提示");
                    dialog.setMainColor(getResources().getColor(R.color.red));
                    dialog.setContent("是否确认退货？");
                    dialog.setOnClickCallback(new OnClickCallback() {
                        @Override
                        public void onClick(BaseDialog dialog, Object number, Object content) {
                            if ((Integer) number == 2) {
                                if ((AboutMyOrderActivity.this).isLogin(true)) {
                                    HttpRequestParams params = new HttpRequestParams("UpdateOrderStatus");
                                    params.addUserId(userData);
                                    params.addBodyParameter("order_id", String.valueOf(list.get(position).getId()));
                                    params.addBodyParameter("edit_type", "return_goods");
                                    x.http().post(params, new HttpCallBack<String>(AboutMyOrderActivity.this, AboutMyOrderActivity.this.getString(R.string.loadding), false) {
                                        @Override
                                        public void onSuccess(String result) {
                                            super.onSuccess(result);
                                            listViewAdapter.notifyDataSetChanged();
                                        }
                                    });
                                }
                            }
                        }
                    });
                    dialog.show();
                }
            });


            //取消订单
            viewHolder.bt_cancel_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseDialog dialog = new BaseDialog(AboutMyOrderActivity.this, BaseDialog.MODE.CONFIRM);
                    dialog.setTitleMain("提示");
                    dialog.setMainColor(getResources().getColor(R.color.black));
                    dialog.setContent("是否删除该订单？");
                    dialog.setOnClickCallback(new OnClickCallback() {
                        @Override
                        public void onClick(BaseDialog dialog, Object number, Object content) {
                            if ((Integer) number == 2) {
                                if ((AboutMyOrderActivity.this).isLogin(true)) {
                                    final HttpRequestParams params = new HttpRequestParams("DelOrder");
                                    params.addUserId(userData);
                                    params.addBodyParameter("order_id", String.valueOf(list.get(position).getId()));
                                    x.http().post(params, new HttpCallBack<String>(AboutMyOrderActivity.this, AboutMyOrderActivity.this.getString(R.string.loadding), false) {
                                        @Override
                                        public void onSuccess(String result) {
                                            super.onSuccess(result);
                                            try {
                                                JSONObject jsonObject = new JSONObject(result);
                                                ToastUtils.showShort(AboutMyOrderActivity.this, jsonObject.getString("msg"));
                                                if (jsonObject.getInt("status") == 1) {
                                                    Intent intent = new Intent(AboutMeAddAddressManagementActivity.ADDRESS_CHANG);
                                                    intent.putExtra("type", 1);
                                                    AboutMyOrderActivity.this.sendBroadcast(intent);
                                                    list.remove(position);
                                                    listViewAdapter.notifyDataSetChanged();
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                    dialog.show();
                }
            });

            /**
             * 更改订单的收货地址
             */
            viewHolder.ll_update_address.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderPosition = position;
                    Intent intent = new Intent();
                    intent.setClass(AboutMyOrderActivity.this,AddAddressActivity.class);
                    startActivityForResult(intent,999);
                }
            });

            viewHolder.gridView.setAdapter(new GridViewAdapter(list.get(position).getGoods_detail()));
            return convertView;
        }

        class ViewHolder {
            private TextView tv_time;
            private HorizontalListView gridView;
            private TextView tv_money;
            private TextView tv_name;
            private TextView tv_tel;
            private TextView tv_address;
            private Button bt_cancel_order;//取消订单
            private Button bt_commit;//结算
            private Button bt_confirm_receipt;//确认收货
            private Button bt_evaluate;//评价
            private Button bt_return_goods;//退货
            private LinearLayout ll_update_address;//修改收货地址
            private TextView tv_ddzt;
        }
    }


    class GridViewAdapter extends BaseAdapter {


        private List<GoodsDetail> gridlist = new ArrayList<>();

        public GridViewAdapter(List<GoodsDetail> gridlist) {

            this.gridlist.clear();
            this.gridlist = gridlist;
        }


        @Override
        public int getCount() {
            return gridlist.size();
        }

        @Override
        public Object getItem(int position) {
            return gridlist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(AboutMyOrderActivity.this, R.layout.item_about_my_order_sp_list);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_photo);
                viewHolder.tv_num = (TextView) convertView.findViewById(R.id.tv_num);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //获取数据
            imageManager.bind(viewHolder.imageView, HttpLocalUtils.getHttpFileUrl(gridlist.get(position).getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_num.setText("x" + gridlist.get(position).getQuantity());
            return convertView;
        }

        class ViewHolder {
            private ImageView imageView;
            private TextView tv_num;
        }
    }

}
